package nom.zh.world.controller;

import nom.zh.world.dto.UserInfo;
import nom.zh.world.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 登录方法
     * @return
     */
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String login(){
        return "login";
    }

    /**
     * 获得Principal
     * 实验性质的方法
     * @return
     */
    @RequestMapping(value = "/getPrincipal", method=RequestMethod.GET)
    @ResponseBody
    @PreAuthorize("hasRole('ADMIN')")
    public User getPrincipal()  {
        User user = (User) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        return user;
    }

    /**
     * 获得登录用户的基本信息
     * @param principal
     * @return
     */
    @RequestMapping(value = "/getUserInfo", method=RequestMethod.GET)
    @ResponseBody
    @PreAuthorize("hasRole('USER')")
    public UserInfo getUserInfo(Principal principal)  {
        return userService.getUserByName(principal.getName());
    }

    /**
     * 向session添加属性
     * @param req
     * @return
     */
    @RequestMapping("/set")
    @ResponseBody
    public String set(HttpServletRequest req) {
        req.getSession().setAttribute("testKey", "testValue");
        return "设置session:testKey=testValue";
    }

    /**
     * 获取session属性对应的值
     * @param req
     * @return
     */
    @RequestMapping("/query")
    @ResponseBody
    public String query(HttpServletRequest req) {
        Object value = req.getSession().getAttribute("testKey");
        return "查询Session：\"testKey\"=" + value;
    }

}
